import 'dart:async';
import 'dart:convert';
import 'dart:developer';

import 'package:flutter/services.dart';
import 'package:logger/logger.dart';
import 'package:sports_new/entity/live/ali_live_message.dart';
import 'package:sports_new/entity/live/live_login_entity.dart';
import 'package:sports_new/server/api/live_api.dart';
import 'package:sports_new/server/ws/ali_im_manager.dart';
import 'package:sports_new/utils/sp_utils.dart';
import 'package:sports_new/view/live/items/gift_effect_view.dart';

class AliMessage{
  AliMessage._internal();
  factory AliMessage() => _instance;
  static final AliMessage _instance = AliMessage._internal();

  LiveLoginEntity? messageAuth;
  final MethodChannel _methodChannel = const MethodChannel('ali_message/method');
  final EventChannel _eventChannel = const EventChannel('ali_message/event');

  Stream messageResp(){
    _methodChannel.setMethodCallHandler((e){
      if(e.method == "errorMsg"){
        AliImManager.recordAdd("errorMsg ${e.arguments}");
      }
      return Future.value(null);
    });
    return _eventChannel.receiveBroadcastStream();
  }

  Future login() async{
    if(messageAuth != null) await logout();
    messageAuth = await LiveApi.loginLiveInfo();
    try {
      var result = await _methodChannel.invokeMethod(
        "login", jsonEncode(messageAuth?.toJson())
      );
      Logger().d(result);
      AliImManager.recordAdd("login $result");
    }catch(e){
      AliImManager.recordAdd("login error ${e}");
       Logger().d(e);
    }
  }

  Future logout() async{
    try {
      var result = await _methodChannel.invokeMethod("logout");
      Logger().d(result);
      AliImManager.recordAdd("logout $result");
    }catch(e){
      Logger().d(e);
      AliImManager.recordAdd("logout error $e");
    }
  }

  Future enterGroup(String groupId) async{
    try {
      var result = await _methodChannel.invokeMethod("enterGroup", groupId);
      Logger().d(result);
      AliImManager.recordAdd("enterGroup $result");
      GiftEffectController().clear();
    }catch(e){
      AliImManager.recordAdd("enterGroup error $e");
      Logger().d(e);
    }
  }

  Future leaveGroup(String groupId,int? roomId) async{
    try {
      var result = await _methodChannel.invokeMethod("leaveGroup", groupId);
      LiveApi.closeLiveRoom(roomId);
      GiftEffectController().clear();
      Logger().d(result);
      AliImManager.recordAdd("leaveGroup $result");
    }catch(e){
      Logger().d(e);
      AliImManager.recordAdd("leaveGroup error $e");
    }
  }
}